<template>
    <el-drawer
      v-model="visible"
      :title="mode === 'add' ? '新增角色' : '编辑角色'"
      direction="rtl"
      size="40%"
    >
      <el-form
        ref="formRef"
        :model="localFormData"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="localFormData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="localFormData.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="visible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </template>
  
  <script setup lang="ts">
  import { ref, watch } from 'vue'
  import type { FormInstance, FormRules,Partial,PropType } from 'element-plus'
  import type { Role } from '@/types'
  

// 定义 props
const props = defineProps({
  modelValue: {
    type: Boolean as PropType<boolean>,
    required: false,
    default: false
  },
  formData: {
    type: Object as PropType<Partial<Role>>,
    required: true
  },
  mode: {
    type: String as PropType<'add' | 'edit'>,
    required: true,
    validator: (value: string) => ['add', 'edit'].includes(value)
  }
})
  


  const emit = defineEmits(['update:modelValue', 'submit'])

  const visible = ref(props.modelValue)
  const formRef = ref<FormInstance>()
  const localFormData = ref<Partial<Role>>({})
  
  // 表单验证规则
  const rules = ref<FormRules>({
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
  })
  
  // 同步父组件visible状态
  watch(
    () => props.modelValue,
    (val) => {
      visible.value = val
    }
  )
  
  watch(visible, (val) => {
    emit('update:modelValue', val)
  })
  
  // 初始化表单数据
  watch(
    () => props.formData,
    (val) => {
      localFormData.value = { ...val }
    },
    { immediate: true }
  )
  
  // 提交表单
  const submitForm = async () => {
    try {
      await formRef.value?.validate()
      emit('submit', localFormData.value as Role)
      visible.value = false
    } catch (e) {
      console.log('表单验证失败')
    }
  }
  </script>